package repository.repo;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import repository.ConnectionProvider;

/**
 * Friend: own_nickname friend_nickname
 */
public class FriendRepo {
    public boolean addFriendIfExist(String own_nickname, String friend_nickname) {
        try {
            Connection con = ConnectionProvider.getConnection();
            Statement stm = con.createStatement();

            // 查询用户是否存在
            String sql_select = "select * from user where nickname ='" + friend_nickname + "'";
            ResultSet rs1 = stm.executeQuery(sql_select);

            if (!rs1.next()) {
                ConnectionProvider.closeConnection(stm, con);
                return false;
            }

            // 添加朋友
            String sql_insert = "insert into friend(own_nickname,friend_nickname)values('" + own_nickname + "','"
                    + friend_nickname + "')";
            int rs2 = stm.executeUpdate(sql_insert);

            ConnectionProvider.closeConnection(stm, con);
            return rs2 <= 0;
        } catch (SQLException e) {
            System.out.println("SQL Exception: " + e.toString());
        }
        return false;
    }

    public ArrayList<String> getFriedList(String own_nickname) {
        try {
            Connection con = ConnectionProvider.getConnection();
            Statement s = con.createStatement();
            String sql = "select friend_nickname from friend where ownID = '" + own_nickname + "'";
            ResultSet rs = s.executeQuery(sql);
            ArrayList<String> list = new ArrayList<>();
            while (rs.next()) {
                list.add(rs.getString(1));
            }
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
